<template>
  <a-card class="body-container">
    <s-tool-bar>
      <template #left>
        <s-button
          v-if="authorize.insert"
          type="primary"
          icon="plus-outlined"
          @click="$refs.add.open()"
          >新增</s-button
        >
        <a-popconfirm
          v-if="authorize.deleteMulti"
          title="确认删除所选数据？"
          ok-text="是"
          cancel-text="否"
          @confirm="deleteMulti"
        >
          <s-button type="danger" icon="delete-outlined">删除</s-button>
        </a-popconfirm>
      </template>
      <template #right>
        <s-button type="primary" icon="redo-outlined" @click="$refs.table.refresh()">刷新</s-button>
      </template>
    </s-tool-bar>
    <s-table
      ref="table"
      bordered
      :scroll="{ y: tableHeight }"
      :columns="columns"
      url="/code/module/pageList"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a
            v-if="authorize.update"
            style="margin-right: 8px"
            @click="$refs.update.open(record.id)"
          >
            <s-icon type="edit-outlined" />编辑
          </a>
          <a-popconfirm
            v-if="authorize.delete"
            title="确认删除此条数据？"
            ok-text="是"
            cancel-text="否"
            @confirm="deleteById(record.id)"
          >
            <a style="margin-right: 8px"> <s-icon type="delete-outlined" />删除 </a>
          </a-popconfirm>
          <a-dropdown :trigger="['click']">
            <a class="ant-dropdown-link" @click.prevent> 更多<s-icon type="down-outlined" /> </a>
            <template #overlay>
              <a-menu>
                <a-menu-item v-if="authorize.genCode" @click="genCode(record.id)">
                  <s-icon type="code-outlined" />生成代码
                </a-menu-item>
                <a-menu-divider />
                <a-menu-item
                  v-if="authorize.updateList"
                  @click="$parent.openTableDesign(record.id)"
                >
                  <s-icon type="table-outlined" />列表设计
                </a-menu-item>
                <a-menu-divider />
                <a-menu-item v-if="authorize.updateForm" @click="$parent.openFormDesign(record.id)">
                  <s-icon type="table-outlined" />表单设计
                </a-menu-item>
                <a-menu-divider />
                <a-menu-item
                  v-if="record.moduleValue.authCheck == '1'"
                  @click="addPermission(record.moduleValue.code, record.moduleValue.name)"
                >
                  <s-icon type="ext-icon-quanxian" />一键录入权限
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </template>
    </s-table>
    <add
      ref="add"
      :items="formItems"
      :init-value="initValue"
      @success="
        () => {
          $refs.table.refresh()
        }
      "
    />
    <update
      ref="update"
      :items="formItems"
      @success="
        () => {
          $refs.table.refresh()
        }
      "
    />
  </a-card>
</template>

<script>
import Add from '.././add/index.vue'
import Update from '.././update/index.vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import ls from '@/utils/Storage'
import { PUT } from '@/api/api'
import axios from 'axios'
const BASIC_URL = import.meta.env.VITE_API_PATH
export default {
  name: 'QueryList',
  components: { Add, Update },
  data() {
    return {
      query: {},
      columns: [],
      formItems: [],
      initValue: {}
    }
  },
  authorize: '/code/module/permissionList',
  created() {
    this.$api.GET('/code/config/selectOne').then((res) => {
      this.initValue = res.data.testData.model
      this.formItems = res.data.formConfig.module.form
      res.data.formConfig.module.list.forEach((item) => {
        let newItem = JSON.parse(JSON.stringify(item))
        newItem.dataIndex = newItem.dataIndex.split('.')
        this.columns.push(newItem)
      })
      this.columns.push({
        title: '操作',
        fixed: 'right',
        key: 'action',
        width: 200
      })
    })
  },
  methods: {
    addPermission(code, name) {
      this.$loading(true)
      let values = {
        text: name,
        value: 'skrivet:' + code + ':basic',
        orderNum: 99,
        remark: name + '的权限。由系统自动录入'
      }
      this.$api
        .PUT('/authority/permission/insert', values)
        .then((res) => {
          let id = res.data
          if (!id) {
            this.$message.warn('录入失败')
            this.$loading(false)
          } else {
            const all = [
              PUT('/authority/permission/insert', {
                parentId: id,
                text: '新增',
                value: 'skrivet:' + code + ':add',
                orderNum: 1,
                remark: name + '的新增权限。由系统自动录入'
              }),
              PUT('/authority/permission/insert', {
                parentId: id,
                text: '修改',
                value: 'skrivet:' + code + ':update',
                orderNum: 2,
                remark: name + '的修改权限。由系统自动录入'
              }),
              PUT('/authority/permission/insert', {
                parentId: id,
                text: '删除',
                value: 'skrivet:' + code + ':delete',
                orderNum: 3,
                remark: name + '的删除权限。由系统自动录入'
              }),
              PUT('/authority/permission/insert', {
                parentId: id,
                text: '列表',
                value: 'skrivet:' + code + ':list',
                orderNum: 4,
                remark: name + '的列表权限。由系统自动录入'
              }),
              PUT('/authority/permission/insert', {
                parentId: id,
                text: '详情',
                value: 'skrivet:' + code + ':detail',
                orderNum: 5,
                remark: name + '的详情权限。由系统自动录入'
              })
            ]
            Promise.all(all)
              .then((allRes) => {
                this.$loading(false)
                this.$message.info('录入成功')
              })
              .catch((e) => {
                this.$message.warn('录入失败')
                this.$loading(false)
              })
          }
        })
        .catch(() => {
          this.$loading(false)
        })
    },
    genCode(id) {
      const token = ls.get(ACCESS_TOKEN)
      this.$loading(true)
      const tokenKey = import.meta.env.VITE_TOKEN_KEY
      const p = {
        responseType: 'blob',
        headers: {}
      }
      p.headers[tokenKey] = token
      axios
        .get(BASIC_URL + '/code/module/genCode/' + id, p)
        .then((res) => {
          this.$loading(false)
          const objectUrl = window.URL.createObjectURL(new Blob([res.data]))
          const downloadA = document.createElement('a')
          downloadA.href = objectUrl
          downloadA.download = id + '.zip'
          downloadA.click()
          window.URL.revokeObjectURL(downloadA.href)
        })
        .catch((e) => {
          this.$message.error('生成失败!')
          this.$loading(false)
        })
    },
    deleteMulti() {
      const keys = this.$refs.table.getSelectedKeys()
      if (keys.length > 0) {
        this.$loading(true)
        this.$api
          .DELETE('/code/module/deleteMulti', { ids: keys.toString() })
          .then(() => {
            this.$loading(false)
            this.$refs.table.search(this.query)
          })
          .catch(() => {
            this.$loading(false)
          })
      }
    },
    deleteById(id) {
      this.$loading(true)
      this.$api
        .DELETE('/code/module/delete', { id: id })
        .then(() => {
          this.$loading(false)
          this.$refs.table.search(this.query)
        })
        .catch(() => {
          this.$loading(false)
        })
    }
  }
}
</script>

<style lang="less" scoped></style>
